<?php

if (!class_exists("stadmincontroller")) {

    class stadmincontroller {

        protected static $_instance = null;
        public $view = null;
        public $config = array();
        public $layout = "default";
        public $actionName = "index";
        public $isAjax = 0;
        public $themePage = "index";

        public function __construct($config) {
            $this->setConfig($config);
            if (isset($_REQUEST ['action'])) {
                $this->actionName = $_REQUEST ['action'];
            }
            $this->layout = $this->config ['default_layout'];
            $this->isAjax = false;
            $this->view = new stthemeview ();
            $this->functions = new adminFunctions($this->config);
            $this->view->config = $this->config;
            $this->option = get_option($this->config['theme_name'] . '_' . $this->config['option_key'] . '_settings');
        }

        public function __destruct() {}

        public function addAdmin() {
            if ($_REQUEST ['ajax'] == 0) {
                $this->addMenuPage();
            } else {
                if ($_REQUEST['page'] == $this->config['theme_name']) {
                    $this->ajaxAction();
                }
            }
        }

        public function ajaxAction() {
            $this->isAjax = true;
            $this->execute();
            die ();
        }

        public static function getInstance() {
            if (null === self::$_instance) {
                self::$_instance = new self ();
            }
            return self::$_instance;
        }

        protected function setConfig($config) {
            $this->config = $config;
            if ($this->actionName == "index") {
                $this->actionName = $config['default_action'];
            }
            
            $this->config['themeDir'] = TEMPLATEPATH . '/admin-functions/';
            $this->config['includePath'] = TEMPLATEPATH . '/stInclude/';
            $this->config['cssUrl'] = WP_CONTENT_URL . '/themes/' . $this->config['theme_name'] . '/admin-functions/css/';
            $this->config['scriptUrl'] = WP_CONTENT_URL . '/themes/' . $this->config['theme_name'] . '/admin-functions/scripts/';
            $this->config['imagesUrl'] = WP_CONTENT_URL . '/themes/' . $this->config['theme_name'] . '/admin-functions/images/';
        }

        public function execute() {
            if (is_callable(array($this, $this->actionName)) == false) {
                die("<br />Action not found: <b>Class: " . $this->config ['theme_name'] . "Controller, Action: " . $this->actionName . "</b> in " . __FILE__);
            }
            $this->registerTabMenu();

            $actionNameCall = $this->actionName;
            $this->$actionNameCall();

            $data = $this->view->getData();
            $data ['current_action'] = $this->actionName;
            $layoutHeader = get_include_contents ( $this->config ['themeDir'] . "/views/layout/header.php", $data );
            $layoutFooter = get_include_contents ( $this->config ['themeDir'] . "/views/layout/footer.php", $data );
            $output = get_include_contents($this->config ['themeDir'] . "/views/{$this->actionName}.php", $data);

            if ($this->isAjax) {
                echo $layoutHeader.$output.$layoutFooter;
            } else {
                $data = $this->view->getData();
                $data ['content'] = $layoutHeader;
                $data ['content'] .= $output;
                $data ['content'] .= $layoutFooter;
                $data ['config'] = $this->config;
                $data ['tabmenus'] = $this->tabMenu;
                $data ['current_action'] = $this->actionName;
                $layout = get_include_contents($this->config ['themeDir'] . "/views/layout/{$this->layout}.php", $data);
                echo $layout;
            }
        }

        public function head() {
            $method = array($this, 'loadSource');
            add_action('admin_head', $method);
        }

        public function loadSource() {
            //this is function import javascript
            echo '<link href="' . $this->config ['cssUrl'] . 'style.css" rel="stylesheet" type="text/css" />' . "\n";
            echo '<link href="' . $this->config ['cssUrl'] . 'custom.css" rel="stylesheet" type="text/css" />' . "\n";
            echo '<script type="text/javascript" src="' . $this->config ['scriptUrl'] . 'jquery-ui-1.8.7.custom.min.js"></script>';
            echo '<script type="text/javascript" src="' . $this->config ['scriptUrl'] . 'jquery.validate.pack.js"></script>';
            echo '<script type="text/javascript" src="' . $this->config ['scriptUrl'] . 'sttheme.js"></script>';
            echo '<script type="text/javascript" src="' . $this->config ['scriptUrl'] . 'ajaxupload.js"></script>';
            echo '<script type="text/javascript" src="' . $this->config ['scriptUrl'] . 'jquery.ui.tooltip.js"></script>';
            echo '<script type="text/javascript" src="' . $this->config ['scriptUrl'] . 'jquery.blockUI.js"></script>';
        }

        public function customHead() {
            $this->customEnqueueScript();
            $method = array($this, 'loadCss');
            add_action('admin_head', $method);
            $method = array($this, 'loadScript');
            add_action("admin_head", $method);
        }

        public function loadCss() {}

        public function loadScript() {}
        
        public function customEnqueueScript() {}

        public function loadmodel($modelName) {
            $className = $modelName . "_model";
            $fileName = $this->config ['includePath'] . "models/{$modelName}.php";
            require_once $fileName;
            $obj = new $className($this->config);
            return $obj;
        }

        public function index() {}

        protected function addMenuPage($capability = '8', $icon = '') {
            if($icon == ''){
                $icon = $this->config['imagesUrl'].'slope-icon.png';
            }
            $method = array($this, 'execute');
            $this->themePage = add_menu_page($this->config ['page_title'], $this->config ['theme_menu_title'], 8, $this->config ['theme_name'], $method, $icon);
            // load only script and css for this theme
            $method = array($this, 'head');
            add_action("admin_print_scripts-$this->themePage", $method);
            $method = array($this, 'customHead');
            add_action("admin_print_scripts-$this->themePage", $method);
        }

        protected function setTabMenu($tabmenus) {
            foreach ($tabmenus as $key => $value) {
                if (count($value) > 1) {
                    foreach ($value as $key_child => $value_child) {
                        $this->tabMenu [$key][$key_child] = $value_child;
                    }
                }else
                    $this->tabMenu [$key] = $value;
            }
        }

        protected function registerTabMenu() {
            if (isset($this->config['admin_tabs'])) {
                $this->setTabMenu($this->config['admin_tabs']);
            }
        }

        public function activationTheme() {}

        public function getAction($action = '', $agrs = ''){
            if($action != '' && !is_object($action)){
                $actionNameCall = $action;
            }
            else{
                $actionNameCall = $this->actionName;
            }
            if($agrs != '' )
                $this->$actionNameCall ($agrs);
            else
                $this->$actionNameCall ();
            $data = $this->view->getData();
            $data ['current_action'] = $actionNameCall;
            $output = get_include_contents ( $this->config ['themeDir'] . "views/{$actionNameCall}.php", $data );

            if($action != '' && !is_object($action)){
                return $output;
            }else{
                echo $output;
            }
        }
        
        protected function updateOption($data = '', $value = ''){
            $option = get_option($this->config['theme_name'].'_'.$this->config['option_key'].'_settings');
            if(is_array($data) >0 ){
                foreach ($data as $key => $value) {
                    $option[$key] = $value;
                }
            }else{
                $option[$data] = $value;
            }

            if(update_option($this->config['theme_name'].'_'.$this->config['option_key'].'_settings', $option)){
                return true;
            }else{
                return false;
            }
        }
        
        public function ajaxPostAction() {
            $save_type = $_POST['type'];
            //Uploads
            if ($save_type == 'upload') {
                $clickedID = $_POST['data']; // Acts as the name
                $filename = $_FILES[$clickedID];
                $filename['name'] = preg_replace('/[^a-zA-Z0-9._\-]/', '', $filename['name']);

                $override['test_form'] = false;
                $override['action'] = 'wp_handle_upload';
                $uploaded_file = wp_handle_upload($filename, $override);
                list($width, $height) = getimagesize($uploaded_file['file']);
                if ($_POST['thumbnail_width'] != '') {
                    $max_w = $_POST['thumbnail_width'];
                    $max_h = round(($max_w * $height) / $width);
                    if (isset($uploaded_file['file'])) {
                        $thumbnail = image_resize($uploaded_file['file'], $max_w, $max_h, true, 'thumb');
                        $thumbnail_url = $upload_dir_url . basename($thumbnail);
                    }
                }

                if (!empty($uploaded_file['error'])) {
                    echo 'Upload Error: ' . $uploaded_file['error'] . "|*| Upload Error";die;
                } else {
                    echo $uploaded_file['url'] . "|*|" . $uploaded_file['file'];die;
                } // Is the Response
            } elseif ($save_type == 'image_remove') {
                $file = $_POST['file']; // Acts as the name
                $img_name = basename($file);
                $img_name = explode('.', $img_name);
                $img_name = $img_name[0];
                $file_thumb = str_replace($img_name, $img_name . '-thumb', $file);
                unlink($file);
                unlink($file_thumb);
            }
        }
    }

}
?>